﻿/// Copyright (c) Microsoft Corporation.  All rights reserved.
using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration.Install;
using Microsoft.Win32;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace DevenvSetupCustomAction
{
    [RunInstaller(true)]
    public partial class DevenvSetup : Installer
    {
        private const string ASSEMBLY_NODE_FIND = "<Assembly>Tcvt.Packages.dll</Assembly>";
        private const string ASSEMBLY_NODE_REPLACE = "<Assembly>{0}</Assembly>";

        public DevenvSetup()
        {
            InitializeComponent();
        }

        public override void Install(IDictionary stateSaver)
        {
            Trace.WriteLine("TCVT Custom Action::Install:: TCVT entered Install custom action.");
            base.Install(stateSaver);

            stateSaver.Add("TargetDir", Context.Parameters["TCVT_TargetDir"].ToString());

            //@"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\9.0\Setup\VS"
            //@"SOFTWARE\Microsoft\VisualStudio\9.0\Setup\VS"
            // First, try to find the 64-bit hive.
            RegistryKey setupKey = Registry.LocalMachine.OpenSubKey(
                  @"SOFTWARE\Wow6432Node\Microsoft\VisualStudio\9.0\Setup\VS");
            if (setupKey == null)
            {
                // Try the default hive if 64-bit hive turns out nothing.
                setupKey = Registry.LocalMachine.OpenSubKey(
                    @"SOFTWARE\Microsoft\VisualStudio\9.0\Setup\VS");
            }
            // If both hives turn out nothing, chances are the version of VS we are
            // looking for is not installed.
            if (setupKey != null)
            {
                Trace.WriteLine("TCVT Custom Action::Install:: Found Key.");
                string devenv = setupKey.GetValue("EnvironmentPath").ToString();
                if (!string.IsNullOrEmpty(devenv))
                {
                    //Process.Start(devenv, "/setup /nosetupvstemplates").WaitForExit();
                    Process.Start(devenv, "/setup").WaitForExit();
                }
                else
                {
                    Trace.WriteLine("TCVT Custom Action::Install:: EnvironmentPath not found.");
                }
            }
            else
            {
                Trace.WriteLine("TCVT Custom Action::Install:: Registry Key Not Found.");
            }
        }

        public override void Commit(IDictionary savedState)
        {
            Trace.WriteLine("TCVT Custom Action::Commit:: TCVT entered Commit custom action.");
            base.Commit(savedState);

            try
            {
                // Copy the Addin file to the common addins location.
                string addinsAllUsersLocation = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                    "Microsoft\\MSEnvShared\\Addins");

                Trace.WriteLine(string.Format("TCVT Custom Action::Commit:: addinsAllUsersLocation: {0}.", addinsAllUsersLocation));

                if (!Directory.Exists(addinsAllUsersLocation))
                    Directory.CreateDirectory(addinsAllUsersLocation);

                string targetDir = (string)savedState["TargetDir"];
                Trace.WriteLine(string.Format("TCVT Custom Action::Commit:: targetDir: {0}.", targetDir));

                // Set the correct path in the add-in:
                string addinLocation = Path.Combine(addinsAllUsersLocation, "TcvtExtensions.AddIn");
                Trace.WriteLine(string.Format("TCVT Custom Action::Commit:: addinLocation: {0}.", addinLocation));

                string sourceFilePath = Path.Combine(targetDir, "TcvtExtensions.AddIn");
                Trace.WriteLine(string.Format("TCVT Custom Action::Commit:: sourceFilePath: {0}.", sourceFilePath));

                File.Copy(sourceFilePath, addinLocation, true);

                // Make sure the file has been copied successfully:
                if (File.Exists(addinLocation))
                {
                    string fileContents = File.ReadAllText(addinLocation, Encoding.Unicode);

                    string sourceAssemblyPath = Path.Combine(targetDir, "Tcvt.Packages.dll");
                    Trace.WriteLine(string.Format("TCVT Custom Action::Commit:: sourceAssemblyPath: {0}.", sourceAssemblyPath));

                    fileContents = fileContents.Replace(ASSEMBLY_NODE_FIND, string.Format(ASSEMBLY_NODE_REPLACE, sourceAssemblyPath));

                    File.WriteAllText(addinLocation, fileContents, Encoding.Unicode);

                    Trace.WriteLine("TCVT Custom Action::Commit:: Successfully updated contents.");
                    Trace.WriteLine(string.Format("TCVT Custom Action::Commit:: Updated File Contents: {0}.", fileContents));
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("TCVT Custom Action::Commit:: Error: Message: {0}.", ex.Message));
                Trace.WriteLine(string.Format("TCVT Custom Action::Commit:: Error: Stack: {0}.", ex.StackTrace));
            }
        }

        public override void Uninstall(IDictionary savedState)
        {
            Trace.WriteLine("TCVT Custom Action::Uninstall:: TCVT entered Uninstall custom action.");
            base.Uninstall(savedState);

            try
            {
                // Copy the Addin file to the common addins location.
                string addinLocation = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
                    "Microsoft\\MSEnvShared\\Addins\\TcvtExtensions.AddIn");

                Trace.WriteLine(string.Format("TCVT Custom Action::Uninstall:: addinLocation: {0}.", addinLocation));

                if (File.Exists(addinLocation))
                {
                    File.Delete(addinLocation);
                    Trace.WriteLine("TCVT Custom Action::Uninstall:: Successfully deleted add-in file.");
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("TCVT Custom Action::Uninstall:: Error: Message: {0}.", ex.Message));
                Trace.WriteLine(string.Format("TCVT Custom Action::Uninstall:: Error: Stack: {0}.", ex.StackTrace));
            }
        }
    }
}
